﻿using Models.DataModel;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Models.DataStore
{
    public partial class Ctrl : Core
    {
        public List<Contribution> GetListContribution(string searchtext = "")
        {
            return db.Contributions.Where(c => c.CompanyName.Contains(searchtext) || c.CompanyNumber.Contains(searchtext) || c.PortName.Contains(searchtext) || c.PortNumber.Contains(searchtext)).ToList();
        }
        public void AddNewContribution(Contribution contribution)
        {
            List<ContributionRate> listRate = db.ContributionRates.Where(c => c.Year == contribution.DateOfContribution.Year && c.PortId == contribution.PortId).ToList();
            ContributionFundAllocation funall;
            foreach (ContributionRate rate in listRate)
            {
                funall = new ContributionFundAllocation();
                funall.ContributionFundAllocationId = Guid.NewGuid();
                funall.ContributionId = contribution.ContributionId;
                funall.FundId = rate.FundId;
                funall.Amount = (decimal)(contribution.NumberOfHours * rate.Rate * rate.Percentage / 100);
                funall.CreatedOn = DateTime.Today;
                funall.Rate = rate.Rate;

                funall.Percentage = rate.Percentage;
                db.ContributionFundAllocations.Add(funall);
            }

            db.Contributions.Add(contribution);
            db.SaveChanges();
        }
        public Contribution GetContributionById(Guid id)
        {
            return db.Contributions.Where(c => c.ContributionId == id).FirstOrDefault();
        }
        public int DeleteSelectedContribution(IEnumerable<Guid> contributionItemDelete)
        {
            try {
                
                List<ContributionFundAllocation> conl = db.ContributionFundAllocations.Where(cp => contributionItemDelete.Contains(cp.ContributionId)).ToList();
                db.ContributionFundAllocations.RemoveRange(conl);

                List<Contribution> list = db.Contributions.Where(cp => contributionItemDelete.Contains(cp.ContributionId)).ToList<Contribution>();
                db.Contributions.RemoveRange(list);
                return db.SaveChanges();
            }
            catch
            {
                return 0;
            }
           
        }
        public int DeleteContribution(Guid id)
        {
            db.ContributionFundAllocations.Remove(db.ContributionFundAllocations.Where(con=>con.ContributionId==id).FirstOrDefault()); 
            var cd = db.Contributions.Where(co => co.ContributionId == id).FirstOrDefault();
            db.Entry(cd).State = EntityState.Deleted;
            return db.SaveChanges();
        }
    }
}
